package cn.ac.iie.ulss.data625.filecontrol;

import cn.ac.iie.ulss.data625.commons.RuntimeEnv;
import cn.ac.iie.ulss.data625.server.Data625StartUp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 用于打印统计参数数据的线程
 *
 * @author: evan
 * @date: 2014-05-25
 */
public class FileControlThread implements Runnable {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");
    static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(FileControlThread.class.getName());

    @Override
    public void run() {
        log.info("start print the count ");
        Calendar cal = Calendar.getInstance();
        cal.set(12, 0);
        cal.set(13, 0);
        cal.set(14, 0);
        Long mtime = cal.getTimeInMillis();
        Calendar newcal = null;
        Date date = null;
        String time = null;

        //首次启动的时候，就得先把文件名搞出来，然后再通过时间去控制不同的文件名
        date = new Date();
        time = dateFormat.format(date);
        Data625StartUp.fileNames.clear();
        for (int i = 0; i < RuntimeEnv.getParamAsInteger(RuntimeEnv.FILE_NUM); i++) {
            String fileName = new StringBuilder().append(RuntimeEnv.getParam(RuntimeEnv.FILE_NAME_COMMON)).append(time).append("_").append(i).toString();
            Data625StartUp.fileNames.add(fileName);
        }
        
        while (true) {
            newcal = Calendar.getInstance();
            newcal.set(12, 0);
            newcal.set(13, 0);
            newcal.set(14, 0);
            if (newcal.getTimeInMillis() > mtime) {
                date = new Date();
                time = dateFormat.format(date);
                //控制新文件名
                Data625StartUp.fileNames.clear();
                for (int i = 0; i < RuntimeEnv.getParamAsInteger(RuntimeEnv.FILE_NUM); i++) {
                    String fileName = new StringBuilder().append(RuntimeEnv.getParam(RuntimeEnv.FILE_NAME_COMMON)).append(time).append("_").append(i).toString();
                    Data625StartUp.fileNames.add(fileName);
                }
                mtime = newcal.getTimeInMillis();
            }
            log.info("now write file: " + Data625StartUp.fileNames);
            try {
                Thread.sleep(30000);
            } catch (InterruptedException ex) {
                log.error(ex, ex);
            }
        }
    }
}
